package com.itzz.spring_zhoneHeng.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itzz.spring_zhoneHeng.base.RestResponse;
import com.itzz.spring_zhoneHeng.base.SystemCode;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//403无权限访问
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        //定义响应格式
        RestResponse fail = RestResponse.fail(SystemCode.AccessDenied.getCode(), SystemCode.AccessDenied.getMessage());
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        //将响应信息转化为json格式
        writer.write(new ObjectMapper().writeValueAsString(fail));
        writer.flush();
        writer.close();
    }
}
